#encoding=utf-8

from django.http import HttpResponse
from django.shortcuts import render
from TPM_WEB.models import User
from TPM_WEB.models import Error
from TPM_WEB.models import Trace
from django.db.models import Q
from django.db import IntegrityError
import datetime

import json

def index(request):
    return render(request, 'index.html')


def user(request):
    return render(request, 'user.html')


def error(request):
    return render(request, 'error.html')

def get_error_name(request):

    all_error = Error.objects.filter(Q(enable=True))

    aa = []
    for i in all_error:
        aa.append({'id': i.id, 'text': i.name,})

    return HttpResponse(json.dumps(aa), content_type='text/html')

def get_error(request):
    page = int(request.POST.get('page')) if request.POST.get('page') else 1
    rows = int(request.POST.get('rows')) if request.POST.get('rows') else 10
    offset = int((page - 1) * rows)

    machine = request.POST.get('machine')
    content = request.POST.get('content')
    department = request.POST.get('department')
    date = request.POST.get('date')
    status = request.POST.get('status')
    error_time = request.POST.get('error_time')

    sort = request.POST.get('sort') if request.POST.get('sort') else 'date'
    order = request.POST.get('order') if request.POST.get('order') else 'asc'

    if order == 'asc':
        order = sort
    elif order == 'desc':
        order = '-' + sort

    result = {}
    all_error = Error.objects.all()
    result["total"] = all_error.count();
    if machine:
        result["total"] = all_error.filter(Q(machine=machine) & Q(enable=True)).count();
        all_error = all_error.filter(Q(machine=machine) & Q(enable=True))
    if content:
        result["total"] = all_error.filter(Q(content=content) & Q(enable=True)).count();
        all_error = all_error.filter(Q(content=content) & Q(enable=True))
    if department:
        result["total"] = all_error.filter(Q(department=department)  & Q(enable=True)).count();
        all_error = all_error.filter(Q(department=department) & Q(enable=True))


    all_error =all_error.filter(Q(enable=True)).order_by(order)[offset:offset + rows]

    aa = []
    for i in all_error:
        aa.append({'id':i.id,'machine': i.machine, 'content': i.content, 'department': i.department, 'date': i.date.strftime('%Y-%m-%d'),
                   'status': i.status, 'error_time': i.error_time,'countermeasure':i.countermeasure})

    result["rows"] = aa;
    return HttpResponse(json.dumps(result), content_type='text/html')


def get_users(request):
    page = int(request.POST.get('page')) if request.POST.get('page') else 1
    rows = int(request.POST.get('rows')) if request.POST.get('rows') else 10
    offset = int((page - 1) * rows)

    worker_number = request.POST.get('worker_number')
    name = request.POST.get('name')
    email = request.POST.get('email')
    phone = request.POST.get('phone')

    sort = request.POST.get('sort') if request.POST.get('sort') else 'worker_number'
    order = request.POST.get('order') if request.POST.get('order') else 'asc'

    if order == 'asc':
        order = sort
    elif order == 'desc':
        order = '-' + sort

    result = {}

    all_user = User.objects.all()
    result["total"] = all_user.count();

    if worker_number :
        result["total"] = all_user.filter(Q(worker_number=worker_number)  & Q(enable=True) ).count();
        all_user =all_user.filter(Q(worker_number=worker_number) & Q(enable=True) )
    if name:
        result["total"] = all_user.filter(Q(name=name)  & Q(enable=True)).count();
        all_user = all_user.filter(Q(name=name)  & Q(enable=True))
    if phone:
        result["total"] = all_user.filter(Q(phone=phone) & Q(enable=True)).count();
        all_user = all_user.filter(Q(phone=phone) & Q(enable=True))
    if email:
        result["total"] = all_user.filter(Q(email=email) & Q(enable=True)).count();
        all_user = all_user.filter(Q(email=email) & Q(enable=True))

    all_user = all_user.filter(Q(enable=True)).order_by(order)[offset:offset + rows]
    aa = []
    for i in all_user:
        aa.append({'name': i.name, 'email': i.email, 'phone': i.phone, 'worker_number': i.worker_number})

    result["rows"] = aa;
    return HttpResponse(json.dumps(result), content_type='text/html')


def save_user(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        name = request.POST.get('name')
        worker_number = request.POST.get('worker_number')
        phone = request.POST.get('phone')
        new_user = User(name=name, worker_number=worker_number, email=email, phone=phone)
        try:
            new_user.save()
        except IntegrityError:
            return HttpResponse(json.dumps({'msg': '错误!工号重复'}), content_type='text/html')
        except BaseException:
            return HttpResponse(json.dumps({'msg': '更新失败，请联系管理员'}), content_type='text/html')
        else:
            return HttpResponse(json.dumps({'success': True}), content_type='text/html')


def update_user(request):
    old_worker_number = request.GET.get('worker_number')

    if request.method == 'POST':
        new_worker_number = request.POST.get('worker_number')
        email = request.POST.get('email')
        name = request.POST.get('name')
        phone = request.POST.get('phone')
    try:
        User.objects.filter(worker_number=old_worker_number).update(email=email, name=name, phone=phone,
                                                                worker_number=new_worker_number)

    except IntegrityError:
        return HttpResponse(json.dumps({'msg': '更新失败，工号必须唯一'}), content_type='text/html')
    except BaseException:
        return HttpResponse(json.dumps({'msg': '更新失败，请联系管理员'}), content_type='text/html')
    else:
        return HttpResponse(json.dumps({'success': True}), content_type='text/html')



def remove_user(request):
    if request.method == 'POST':
        worker_number = request.POST.get('worker_number')

    try:
        User.objects.filter(worker_number=worker_number).update(enable=False)
    except BaseException:
        return HttpResponse(json.dumps({'msg': '删除失败，请联系管理员'}), content_type='text/html')
    else:
        return HttpResponse(json.dumps({'success': True}), content_type='text/html')



def save_error(request):
    if request.method == 'POST':
        machine = request.POST.get('machine')
        content = request.POST.get('content')
        department = request.POST.get('department')
        countermeasure = request.POST.get('countermeasure')
        date = request.POST.get('date')
        status = request.POST.get('status')
        error_time = request.POST.get('error_time')
        new_error = Error(machine=machine, content=content, department=department, countermeasure=countermeasure,
                          date=date, status=status,error_time=error_time,)
        try:
            new_error.save()
        except IntegrityError:
            return HttpResponse(json.dumps({'msg': '错误！编号必须唯一'}), content_type='text/html')
        except BaseException:
            return HttpResponse(json.dumps({'msg': '添加失败，请联系管理员'}), content_type='text/html')
        else:
            return HttpResponse(json.dumps({'success': True}), content_type='text/html')




def update_error(request):
    old_id = request.GET.get('id')

    if request.method == 'POST':
        machine = request.POST.get('machine')
        content = request.POST.get('content')
        department = request.POST.get('department')
        countermeasure = request.POST.get('countermeasure')
        date = request.POST.get('date')
        status = request.POST.get('status')
        error_time = request.POST.get('error_time')

        try:
            Error.objects.filter(id=old_id).update(department=department,machine=machine, content=content, countermeasure=countermeasure,date=date, status=status,error_time=error_time,)
        except BaseException:
            return HttpResponse(json.dumps({'msg': '失败，请联系管理员'}), content_type='text/html')
        else:
            return HttpResponse(json.dumps({'success': True}), content_type='text/html')



def remove_error(request):
    if request.method == 'POST':
        id = request.POST.get('id')

    try:
        Error.objects.filter(id=id).update(enable=False)
    except BaseException:
        return HttpResponse(json.dumps({'msg': '失败，请联系管理员'}), content_type='text/html')
    else:
        return HttpResponse(json.dumps({'success': True}), content_type='text/html')


def trace(request):
    all_user = User.objects.filter(enable=True)
    all_error = Error.objects.filter(enable=True)

    return render(request, 'trace.html',{'all_user':all_user,'all_error':all_error})

def get_trace(request):
    page = int(request.POST.get('page')) if request.POST.get('page') else 1
    rows = int(request.POST.get('rows')) if request.POST.get('rows') else 10
    offset = int((page - 1) * rows)

    sort = request.POST.get('sort') if request.POST.get('sort') else 'date'
    order = request.POST.get('order') if request.POST.get('order') else 'asc'
    if sort == 'error_sn':
        sort = 'error'

    if order == 'asc':
        order = sort
    elif order == 'desc':
        order = '-' + sort

    sn = request.POST.get('sn')
    machine = request.POST.get('machine')
    content = request.POST.get('content')
    date = request.POST.get('date')
    device_sn = request.POST.get('device_sn')
    device_name = request.POST.get('device_name')

    result = {}

    all_plan = Plan.objects.all()
    result["total"] = all_plan.count();
    all_plan = Plan.objects.all()

    if plan_id:
        result["total"] = all_plan.filter(id=plan_id).count();
        all_plan = all_plan.filter(id=plan_id)
    if date:
        result["total"] = all_plan.filter(Q(date=date)).count();
        all_plan = all_plan.filter(Q(date=date))
    if check_man:
        result["total"] = all_plan.filter(Q(check_man_id=check_man)).count();
        all_plan = all_plan.filter(Q(check_man_id=check_man))
    if comfirm_man:
        result["total"] = all_plan.filter(Q(comfirm_man_id=comfirm_man)).count();
        all_plan = all_plan.filter(Q(comfirm_man_id=comfirm_man))
    if device_sn:
        result["total"] = all_plan.filter(Q(error_id=device_sn)).count();
        all_plan = all_plan.filter(Q(error_id=device_sn))
    if device_name:
        result["total"] = all_plan.filter(Q(error_id=device_name)).count();
        all_plan = all_plan.filter(Q(error_id=device_name))

    all_plan = all_plan.order_by(order)[offset:offset + rows]

    aa = []
    for i in all_plan:
        if i.date:
            aa.append({'id':i.id,'error': i.error.name,'date': i.date.strftime('%Y-%m-%d'), 'check_man': i.check_man.name, 'comfirm_man': i.comfirm_man.name,
                       'is_check':i.is_check,'is_comfirm':i.is_comfirm,'error_sn': i.error.sn})#
        else:
            aa.append(
                {'error': i.error.name,'check_man': i.check_man.name,'error_id': i.error.id,'check_man_id': i.check_man.id,
                 'comfirm_man': i.comfirm_man.name,'comfirm_man_id': i.comfirm_man.id,'id':i.id,'is_check':i.is_check,'is_comfirm':i.is_comfirm,'error_sn': i.error.sn})  #
    result["rows"] = aa;

    return HttpResponse(json.dumps(result), content_type='text/html')

# def save_plan(request):
#     if request.method == 'POST':
#         error = request.POST.get('error_id')
#         begin_date = request.POST.get('date')
#         check_man = request.POST.get('check_man_id')
#         comfirm_man = request.POST.get('comfirm_man_id')
#         end_date = request.POST.get('end_date') if request.POST.get('end_date') else begin_date
#         date_list = []
#         begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
#         end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
#         if end_date < begin_date:
#             return HttpResponse(json.dumps({'msg': '添加失败，结束时间必须大于开始时间'}), content_type='text/html')
#         while begin_date <= end_date:
#             date_list.append(begin_date)
#             begin_date += datetime.timedelta(days=1)
#
#         for date in date_list:
#             new_Plan = Plan(error_id=error,check_man_id=check_man, comfirm_man_id=comfirm_man,date=date)
#             try:
#                 new_Plan.save()
#             except BaseException:
#                 return HttpResponse(json.dumps({'msg': '添加失败'}), content_type='text/html')
#
#         return HttpResponse(json.dumps({'success': True}), content_type='text/html')

# def update_plan(request):
#     old_id = request.GET.get('id')
#
#     if request.method == 'POST':
#         error = request.POST.get('error_id')
#         date = request.POST.get('date')
#         check_man = request.POST.get('check_man_id')
#         comfirm_man = request.POST.get('comfirm_man_id')
#         try:
#             Plan.objects.filter(id=old_id).update(error_id=error,check_man_id=check_man, comfirm_man_id=comfirm_man,date=date)
#         except BaseException:
#             return HttpResponse(json.dumps({'msg': '更新失败'}), content_type='text/html')
#         else:
#             return HttpResponse(json.dumps({'success': True,'error':error,'date':date,'check_man':check_man,'comfirm_man':comfirm_man}), content_type='text/html')

# def remove_plan(request):
#     if request.method == 'POST':
#         id = request.POST.get('id')
#
#     try:
#         Plan.objects.filter(id=id).delete()
#     except BaseException:
#         return HttpResponse(json.dumps({'msg': '删除失败'}), content_type='text/html')
#     else:
#         return HttpResponse(json.dumps({'success': True}), content_type='text/html')
#

def confirm(request):
    plan_id = request.GET.get('id')
    confirm_type = request.GET.get('type')

    #checkman=0

    try:
        if int(confirm_type) == 0:
            Plan.objects.filter(id=int(plan_id)).update(is_check=True)
        elif int(confirm_type) == 1:
            Plan.objects.filter(id=int(plan_id)).update(is_comfirm=True)
    except BaseException:
        return HttpResponse('<H1>失败</H1>', content_type='text/html')
    else:
        return HttpResponse('<H1>成功</H1>', content_type='text/html')


def export_excel(request):
    data = xlrd.open_workbook('F:\\source\\TPM_WEB\\template.xls')
    #all_plan = Plan.objects.filter(Q(is_check=True) & Q(is_comfirm=True))
    all_plan = Plan.objects.all()
    for item in all_plan:
        #if item.error.name == u'热压机':
        day = int(item.date.strftime('%d'))
        print type(day)
        oldWb = xlrd.open_workbook('F:\\source\\TPM_WEB\\template.xls', formatting_info=True);
        newWb = copy(oldWb);
        newWs = newWb.get_sheet(0);
        borders = xlwt.Borders()
        borders.left = 1
        borders.right = 1
        borders.top = 1
        borders.bottom = 1


        style = xlwt.XFStyle()
        style.borders = borders
        
        newWs.write(16, 2+day, "V",style);
        newWs.write(1, 2, u"设备编号:"+ item.error.sn);
        newWs.write(1, 27, item.date.strftime('%Y')+u"年"+item.date.strftime('%m')+u'月');
        print"write new values ok";
        
    newWb.save('F:\\source\\TPM_WEB\\template2.xls')
    print"save with same name ok";
    return HttpResponse(json.dumps({'success': True}), content_type='text/html')
